// pages/buy/buy.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    domain: app.globalData.domain,
    payShow: false,
    items: [
      { value: '1', name: '微信', },
    ],
    userInfo: app.globalData.userInfo,
    payType: 1,
    isTips: false,
    can_number: 440,//弹窗高度
    buyNumber: 1,  //购买数量
    number: 0, // 点击支付的 已购买期数
    list_index: 0,  //选中的list下标
    // 打折
    discount: { discount_state: 0, discount_periods: 0, discount: 0, discount_time: '', price: 0 },
    // 原价
    initialPrice: 0,
    // 实付
    finalPrice: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (app.globalData.userInfo != null) {
      this.setData({
        'userInfo': app.globalData.userInfo
      })
    }
    this.getBuy()
    this.getTips()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getBuy() {
    var that = this
    app.call.getData('wxapp/getBuy', function (data) {
      let list = data.data;
      list.map(item => {
        // 月票开售状态 0未开放 1已开放
        item.monthly_open_state = 0;
        // 没有值的情况下 默认直接开放 兼容以前的数据
        if (item.monthly_open_time == '') item.monthly_open_state = 1;
        // 如果当前时间大于 月票开售时间 则开售
        else if (new Date() > new Date(item.monthly_open_time)) item.monthly_open_state = 1;
      })
      that.setData({ list: list })
    }, function () { });
  },
  pay(e) {
    var can_number = 440;
    if (e.currentTarget.dataset.can_number == 1) {
      can_number = 540;
    }
    this.setData({
      payShow: true,
      member_room_id: e.currentTarget.dataset.id,
      room_id: e.currentTarget.dataset.room_id,
      serve_id: e.currentTarget.dataset.serve_id,
      can_number: can_number,
      list_index: e.currentTarget.dataset.index,
      // discount: { discount_state: 0, discount_periods: 0, discount: 0, discount_time: '' }
      // 折扣相关信息
      'discount.discount_state': e.currentTarget.dataset.discount_state,
      'discount.discount_periods': e.currentTarget.dataset.discount_periods,
      'discount.discount': e.currentTarget.dataset.discount,
      'discount.discount_time': e.currentTarget.dataset.discount_time,
      'discount.price': e.currentTarget.dataset.price,
      number: e.currentTarget.dataset.number
    })

    // 初次计算原价和实付
    let initialPrice = parseFloat((this.data.buyNumber * this.data.discount.price).toFixed(2)),
      finalPrice = initialPrice;

    // 开启打折 并且 在有效期内
    if (this.data.discount.discount_state == 1 && new Date() < new Date(this.data.discount.discount_time)) {
      // 如果已购期数+当前购买期数大于等于 打折期数上限 则打折
      if (this.data.number + this.data.buyNumber >= this.data.discount.discount_periods) {
        finalPrice = parseFloat((finalPrice * this.data.discount.discount).toFixed(2));
      }
    }

    this.setData({ initialPrice, finalPrice })
  },
  cancelPay() {
    this.setData({
      payShow: false,
      member_room_id: 0,
      room_id: 0,
      serve_id: 0,
      buyNumber: 1,
    })
  },
  tipShow() {
    var that = this
    wx.showModal({
      title: '月票按自然月计算，现已接近月底，是立即生效还是下个月生效',
      confirmText: "立即生效",
      cancelText: "下月生效",
      success: function (res) {
        if (res.confirm) {
          that.setData({
            effect: 'now'
          })
        } else if (res.cancel) {
          that.setData({
            effect: 'next'
          })
        }
        that.createOrder()
      }
    })
  },
  createOrder() {
    var data = this.data;
    if (data.isTips != -1 && data.serve_id == data.isTips && data.tip_ids.indexOf(data.member_room_id) != -1) {
      data.tip_ids.splice(data.tip_ids.indexOf(data.member_room_id), 1);
      this.setData({
        tip_ids: data.tip_ids
      })
      this.tipShow()
      return;
    }
    if (!('member_room_id' in data) || data.member_room_id == 0) {
      app.showTip('无效请求');
      return;
    }
    if (!('room_id' in data) || data.room_id == 0) {
      app.showTip('无效请求');
      return;
    }
    if (!('serve_id' in data) || data.serve_id == 0) {
      app.showTip('无效请求');
      return;
    }
    if (!('payType' in data) || data.payType == 0) {
      app.showTip('无效请求');
      return;
    }

    if (!('buyNumber' in data) || data.buyNumber == 0) {
      app.showTip('无效请求');
      return;
    }
    var postData = {
      member_room_id: data.member_room_id,
      room_id: data.room_id,
      serve_id: data.serve_id,
      payType: data.payType,
      number: data.buyNumber
    }
    if ('effect' in data) {
      postData.effect = data.effect
    }
    var that = this
    app.call.request('wxapp/createOrder', postData, function (data) {
      if (typeof data.data == 'number') {
        app.showTip('支付成功');
        that.setData({
          payShow: false,
          member_room_id: 0,
          room_id: 0,
          serve_id: 0,
          'userInfo.balance': parseFloat((parseFloat(that.data.userInfo.balance) - parseFloat(data.data)).toFixed(2)),
          buyNumber: 1,
        })
        setTimeout(function () {
          that.getBuy();
          that.getTips()
        }, 2000)

      } else {
        wx.requestPayment({
          'timeStamp': data.data.timeStamp,
          'nonceStr': data.data.nonceStr,
          'package': data.data.package,
          'signType': 'MD5',
          'paySign': data.data.paySign,
          'success': function (res) {
            app.showTip('支付成功');
            that.setData({
              payShow: false,
              member_room_id: 0,
              room_id: 0,
              serve_id: 0,
              buyNumber: 1
            })
            that.getBuy();
            that.getTips()
          },
          'fail': function (res) {
            console.log(res);
          }
        });
      }


    }, function () { });
  },
  radioChange(e) {
    this.setData({
      payType: e.detail.value
    })
  },
  getTips() {
    var that = this
    app.call.getData('wxapp/getTips', function (data) {
      if (data.data == -1) {
        that.setData({
          isTips: data.data,
        })
      } else {
        that.setData({
          isTips: data.data.serve_id,
          tip_ids: data.data.tip_ids
        })
      }

    }, function () { });
  },
  log(e) {
    wx.navigateTo({
      url: '/pages/ticket/ticket?room_id=' + e.currentTarget.dataset.room_id
    });
  },
  jian() {
    if (!(this.data.list_index in this.data.list) || !this.data.list[this.data.list_index].hasOwnProperty('periods')) {
      app.showTip('当前购买的服务不支持加减购买数量');
      return;
    }
    var number = parseInt(this.data.buyNumber);
    if (number - 1 < 1) {
      number = 1
    } else {
      number = number - 1
    }
    this.setData({
      buyNumber: number
    })

    // 初次计算原价和实付
    let initialPrice = parseFloat((this.data.buyNumber * this.data.discount.price).toFixed(2)),
      finalPrice = initialPrice;
    console.log(this.data.discount);
    // 开启打折 并且 在有效期内
    if (this.data.discount.discount_state == 1 && new Date() < new Date(this.data.discount.discount_time)) {
      // 如果已购期数+当前购买期数大于等于 打折期数上限 则打折
      if (this.data.number + this.data.buyNumber >= this.data.discount.discount_periods) {
        finalPrice = parseFloat((finalPrice * this.data.discount.discount).toFixed(2));
      }
    }

    this.setData({ initialPrice, finalPrice })
  },

  jia() {
    if (!(this.data.list_index in this.data.list) || !this.data.list[this.data.list_index].hasOwnProperty('periods')) {
      app.showTip('当前购买的服务不支持加减购买数量');
      return;
    }
    var canBuy = parseInt(this.data.list[this.data.list_index].periods) - parseInt(this.data.list[this.data.list_index].number)
    var number = parseInt(this.data.buyNumber);
    if (number + 1 > canBuy) {
      app.showTip('当前购买的服务数量已达最大购买数');
      return;
    }
    this.setData({
      buyNumber: number + 1
    })

    // 初次计算原价和实付
    let initialPrice = parseFloat((this.data.buyNumber * this.data.discount.price).toFixed(2)),
      finalPrice = initialPrice;
    // 开启打折 并且 在有效期内
    if (this.data.discount.discount_state == 1 && new Date() < new Date(this.data.discount.discount_time)) {
      // 如果已购期数+当前购买期数大于等于 打折期数上限 则打折
      if (this.data.number + this.data.buyNumber >= this.data.discount.discount_periods) {
        finalPrice = parseFloat((finalPrice * this.data.discount.discount).toFixed(2));
      }
    }

    this.setData({ initialPrice, finalPrice })
  },
  bindManual(e) {
    var canBuy = parseInt(this.data.list[this.data.list_index].periods) - parseInt(this.data.list[this.data.list_index].number)
    var number = e.detail.value
    if (parseInt(number) < 1) {
      this.setData({
        buyNumber: 1
      })
    } else if (parseInt(number) > parseInt(canBuy)) {
      this.setData({
        buyNumber: canBuy
      })
      return;
    } else {
      this.setData({
        buyNumber: number
      })
    }

    // 初次计算原价和实付
    let initialPrice = parseFloat((this.data.buyNumber * this.data.discount.price).toFixed(2)),
      finalPrice = initialPrice;
    // 开启打折 并且 在有效期内
    if (this.data.discount.discount_state == 1 && new Date() < new Date(this.data.discount.discount_time)) {
      // 如果已购期数+当前购买期数大于等于 打折期数上限 则打折
      if (this.data.number + this.data.buyNumber >= this.data.discount.discount_periods) {
        finalPrice = parseFloat((finalPrice * this.data.discount.discount).toFixed(2));
      }
    }

    this.setData({ initialPrice, finalPrice })

  },
  // 自主登记
  goRegister() {
    wx.navigateTo({ url: '/pages/register/register' });
  },
  // 加满
  buyNumberAll() {
    var canBuy = parseInt(this.data.list[this.data.list_index].periods) - parseInt(this.data.list[this.data.list_index].number);
    this.setData({ buyNumber: canBuy })


    // 初次计算原价和实付
    let initialPrice = parseFloat((this.data.buyNumber * this.data.discount.price).toFixed(2)),
      finalPrice = initialPrice;
    // 开启打折 并且 在有效期内
    if (this.data.discount.discount_state == 1 && new Date() < new Date(this.data.discount.discount_time)) {
      // 如果已购期数+当前购买期数大于等于 打折期数上限 则打折
      if (this.data.number + this.data.buyNumber >= this.data.discount.discount_periods) {
        finalPrice = parseFloat((finalPrice * this.data.discount.discount).toFixed(2));
      }
    }

    this.setData({ initialPrice, finalPrice })
  },
})